﻿// TestFor_NatClient.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//stun 协议客户端示例代码

#include "pch.h"
#include <WinSock2.h>
using namespace std;
#include "../../../../NetEngine_Windows/NetEngine_SourceCode/XyRyNet_CommHdr.h"
#include "../../../../NetEngine_Windows/NetEngine_SourceCode/NetEngine_Client/NetClient_Socket/NetClient_Define.h"
#include "../../../../NetEngine_Windows/NetEngine_SourceCode/NetEngine_Client/NetClient_Socket/NetClient_Error.h"
#include "../../../../NetEngine_Windows/NetEngine_SourceCode/NetEngine_RfcComponents/RfcComponents_NatClient/NatClient_Define.h"
#include "../../../../NetEngine_Windows/NetEngine_SourceCode/NetEngine_RfcComponents/RfcComponents_NatClient/NatClient_Error.h"

#pragma comment(lib,"Ws2_32.lib")
#pragma comment(lib,"../../../../NetEngine_Windows/NetEngine_SourceCode/Debug/NetClient_Socket.lib")
#pragma comment(lib,"../../../../NetEngine_Windows/NetEngine_SourceCode/Debug/RfcComponents_NatClient.lib")

int main()
{
	WSADATA st_WSAData;
	WSAStartup(MAKEWORD(2, 2), &st_WSAData);

	SOCKET m_Socket;
	int nMsgLen = 2048;
	TCHAR tszMsgBuffer[2048];
	UINT nToken[4];
	RFCCOMPONENTS_NATSTUN st_NatClient;

	memset(&st_NatClient, '\0', sizeof(RFCCOMPONENTS_NATSTUN));
	memset(tszMsgBuffer, '\0', sizeof(tszMsgBuffer));
	memset(&nToken, '\0', sizeof(nToken));

	if (!NetClient_UDPSelect_Create(&m_Socket, "129.211.96.206", 3478))
	{
		printf("创建套接字失败!,错误:%X", NatClient_GetLastError());
		return -1;
	}

	if (!RfcComponents_StunNat_Request(tszMsgBuffer, &nMsgLen, RFCCOMPONENTS_NATCLIENT_PROTOCOL_STUN_BINDREQ, nToken))
	{
		printf("构建请求包缓冲区错误!");
		return -1;
	}
	if (!NetClient_UDPSelect_SendMsg(m_Socket, tszMsgBuffer, nMsgLen))
	{
		printf("发送数据失败!,错误:%X",NetClient_GetLastError());
		return -1;
	}

	nMsgLen = 2048;
	memset(tszMsgBuffer, '\0', sizeof(tszMsgBuffer));
	if (!NetClient_UDPSelect_Recv(m_Socket, tszMsgBuffer, &nMsgLen,FALSE))
	{
		printf("接受数据失败!,错误:%X", NetClient_GetLastError());
		return -1;
	}

	if (!RfcComponents_StunNat_Response(tszMsgBuffer,nMsgLen, &st_NatClient))
	{
		printf("处理数据失败!,错误:%X", NatClient_GetLastError());
		return -1;
	}

	NetClient_UDPSelect_Close(m_Socket);
	WSACleanup();
	return 1;
}